﻿using AutoMapper;
using MD5Hash;
using MediatR;
using RBAC.Domain;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.User;
using System.Transactions;

namespace RBAC.Write.Api.Application.Handler.User
{
    public class CreateUserHandler : IRequestHandler<CreateUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly ILogger<CreateUserHandler> logger;
        private readonly IMapper mapper;
        private readonly IBaseRepository<UserRoleModel> userRoleRepository;

        public CreateUserHandler(IBaseRepository<UserModel> userRepository, ILogger<CreateUserHandler> logger, IMapper mapper, IBaseRepository<UserRoleModel> userRoleRepository)
        {
            this.userRepository = userRepository;
            this.logger = logger;
            this.mapper = mapper;
            this.userRoleRepository = userRoleRepository;
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var user = mapper.Map<UserModel>(request);
            user.Password = user.Password.GetMD5();
            using (TransactionScope tran = new TransactionScope())
            {
                try
                {
                    var r1 = userRepository.Create(user);

                    foreach (var item in request.RoleId)
                    {
                        var userrole = new UserRoleModel()
                        {
                            UserId = user.Id,
                            RoleId = item,
                        };
                        var r2 = userRoleRepository.Create(userrole);
                    }
                    tran.Complete();
                    res.Code = APIEnums.Success;
                    res.Data = r1;
                    res.Msg = "添加成功";
                    logger.LogInformation($"添加用户{request.UserName}成功");
                }
                catch (Exception)
                {
                    res.Code= APIEnums.Error;
                    res.Msg = "添加用户失败";
                    res.Data = 0;
                    logger.LogError("添加用户失败");
                    throw;
                }
            }
            return Task.FromResult(res);

        }
    }
}
